package cn.iocoder.mall.pay.application.controller.users;

import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.common.utils.common.system.util.JwtUtil;
import cn.iocoder.common.utils.common.util.DateUtils;
import cn.iocoder.mall.pay.api.PayRefundService;
import cn.iocoder.mall.pay.api.constant.PayChannelEnum;
import cn.iocoder.mall.user.api.AppMessageService;
import cn.iocoder.mall.user.api.constant.AppMessageTypeEnum;
import cn.iocoder.mall.user.api.dto.AppMessageDTO;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/users/refund") // TODO 芋艿，理论来说，是用户无关的。这里先酱紫先~
public class UsersPayRefundController {
    @Reference(validation = "true",version = "${dubbo.consumer.AppMessageService.version}")
    AppMessageService appMessageService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Reference(validation = "true", version = "${dubbo.provider.PayRefundService.version}")
    private PayRefundService payRefundService;

    @PostMapping("/notify/refund")
    public String pingxxRefundSuccess(@RequestBody String xmlData) throws IOException {
        logger.info("[pingxxRefundSuccess][被回调]");

        CommonResult<Boolean> result = payRefundService.updateRefundSuccess(PayChannelEnum.WEIXIN_APP.getId(), xmlData);
        if (result.isError()) {
            return "failure";
        }
        AppMessageDTO appMessageDTO = new AppMessageDTO();
        appMessageDTO.setContent("退款成功");
        appMessageDTO.setTitle("退款");
        appMessageDTO.setCreator("");
        appMessageDTO.setType(AppMessageTypeEnum.PAYMENT_NOTICE.getValue());
        appMessageDTO.setReceiver(JwtUtil.getUserIdByToken());
        appMessageDTO.setTemplateId(1);
        appMessageDTO.setCreateTime(DateUtils.getDate());
        appMessageDTO.setEntitiesId("");
        appMessageService.sendAppMessageToUser(appMessageDTO);
        return WxPayNotifyResponse.success("成功");
    }

}
